<?php
namespace app\controller;

use app\BaseController;
use think\facade\Request;
use think\facade\Db;
use think\Exception;

class User extends BaseController
{
    //查询所有非根用户
    public function get_UserInfo()
    {
        $userId = $this->request->auth['data']->user->user_id;

        $current_page = Request::param('current_page');
        $page_size = Request::param('page_size');

        // 根据用户ID获取公司ID
        $companyId = Db::name('user')->where('user_id', $userId)->value('user_company_id');


        // 查询当前公司下的所有非根用户
        $nonRootUsers = Db::name('user')
            ->where('user_company_id', $companyId)
            ->where('user_root', 0) // 假设user_root为0表示非根用户
            ->where('user_deleted', 0)
            ->order('user_id', 'desc') // 假设按id降序排列
            ->page($current_page, $page_size)
            ->select()->toArray();


        // 获取总数和总页数
        $total = Db::name('user')
            ->where('user_company_id', $companyId)
            ->where('user_root', 0)
            ->where('user_deleted', 0)
            ->count();
        $totalPages = ceil($total / $page_size);


        // 获取每个非根用户的角色和分支信息
        $userRolesInfo = [];
        $userBranchesInfo = [];

        if (!empty($nonRootUsers)) {
            $userIds = array_column($nonRootUsers, 'user_id');

            // 获取角色信息
            $roles = Db::name('role')
                ->alias('r')
                ->join('user_role ur', 'r.role_id = ur.role_id')
                ->whereIn('ur.user_id', $userIds)
                ->field('ur.user_id, r.role_id as role_id, r.role_name as role_name')
                ->select();
            foreach ($roles as $role) {
                $userRolesInfo[$role['user_id']][] = [
                    'role_id' => $role['role_id'],
                    'role_name' => $role['role_name'],
                ];
            }

//            // 获取分支信息
//            $branches = Db::name('branch')
//                ->alias('b')
//                ->join('user_branch ub', 'b.branch_id = ub.branch_id')
//                ->whereIn('ub.user_id', $userIds)
//                ->field('ub.user_id, b.branch_id as branch_id, b.branch_name as branch_name')
//                ->select();
//            foreach ($branches as $branch) {
//                $userBranchesInfo[$branch['user_id']][] = [
//                    'branch_id' => $branch['branch_id'],
//                    'branch_name' => $branch['branch_name'],
//                ];
//            }
        }

        // 获取总角色
        $roles = Db::name('role')->whereIn('role_company_id',$companyId)->select();

//        //获取总分店
//        $branchs = Db::name('branch')->whereIn('branch_company_id',$companyId)->select();

        // 组装结果数据
        $result = [];
        foreach ($nonRootUsers as $user) {
            $result[] = [
                'user_id'=>$user['user_id'],
                'user_username' => $user['user_username'],
                'user_name' => $user['user_name'],
                'user_phone' => $user['user_phone'],
                'user_sex' => $user['user_sex'] == 1 ? '男' : '女',
                'user_creationtime' => substr($user['user_creationtime'],0,10),
                'user_updatime' => substr($user['user_updatime'],0,10),
                'user_switch' => $user['user_switch'],
                'role' => isset($userRolesInfo[$user['user_id']]) ? $userRolesInfo[$user['user_id']] : [],
            ];
        }
        $data = [

            'data' => $result,
            'total' => $total,
            'totalPages' => $totalPages,

        ];
        // 返回结果，包含总数、总页数以及分页数据
        return json([

            'code' => 200,
            'msg' => 'Success',
            'data' => $data,
            'allrole' => $roles,

        ]);


    }





    //修改用户信息接口
    public function Update_UserInfo()
    {
        $user_id = Request::param('id');
        $data=Request::param('data');

        // 验证参数
        if (empty($user_id) || !is_array($data)) {
            return json(['code' => 400, 'msg' => '参数错误']);
        }


        try {
            // 开启事务
            Db::startTrans();

            // 处理用户信息更新

                $userUpdateData = $data;

                //检查data对象是否包含user_role或包含user_branch这两个数组键,如果包含则去除这两个数组键
                if (isset($userUpdateData['user_role'])) {
                    unset($userUpdateData['user_role']);
                }
                if (isset($userUpdateData['user_branch'])) {
                    unset($userUpdateData['user_branch']);
                }
                $updateData = $userUpdateData;





                // 如果密码被传入并且不为空，进行MD5加密
                if (isset($updateData['user_password']) && !empty($updateData['user_password'])) {
                    $updateData['user_password'] = md5($updateData['user_password']);
                }


                // 更新 user 表
                Db::name('user')->where('user_id', $user_id)->update($updateData);



            // 处理用户与分支机构关系更新
            if (isset($data['user_branch'])) {
                $userBranchData = $data['user_branch'];



                // rr
                Db::name('user_branch')->where('user_id', $user_id)->delete();

                // 插入新的关联记录
                foreach ($userBranchData as $branch) {
                    Db::name('user_branch')->insert([
                        'user_id' => $user_id,
                        'branch_id' => $branch,
                    ]);

                }
            }

            // 处理用户与角色关系更新
            if (isset($data['user_role'])) {
                $userRoleData = $data['user_role'];

                // 删除旧的关联记录
                Db::name('user_role')->where('user_id', $user_id)->delete();

                // 插入新的关联记录
                foreach ($userRoleData as $role) {
                    Db::name('user_role')->insert([
                        'user_id' => $user_id,
                        'role_id' => $role,
                    ]);
                }
            }

            // 提交事务
            Db::commit();

            // 返回成功信息
            return json(['code'=>200,'msg'=>'更新成功']);
        } catch (Exception $e) {
            // 发生错误，回滚事务
            Db::rollback();

            // 记录错误或返回错误信息
            return json(['msg' => 'Failed to update user information: ' . $e->getMessage()], 500);
        }




    }

    //新增用户接口
    public function Insert_UserInfo()
    {

        //用户的公司id
        $company_id = $this->request->auth['data']->user->user_company_id;


        $data=Request::param('data');
        //将用户的公司id放入data数组中
        $data['user_company_id'] = $company_id;
        $data['user_root']=0;
        $data['user_switch']=1;

        // 验证参数
        if (!is_array($data)) {
            return json(['code' => 400, 'msg' => '参数错误']);
        }

        //验证用户名是否存在
        if (Db::name('user')->where('user_username', $data['user_username'])->find()) {
            return json(['code' => -2, 'msg' => '用户名已存在']);
        }



        try {
            // 开启事务
            Db::startTrans();

            // 处理用户信息更新

            $userUpdateData = $data;

            //检查data对象是否包含user_role或包含user_branch这两个数组键,如果包含则去除这两个数组键
            if (isset($userUpdateData['user_role'])) {
                unset($userUpdateData['user_role']);
            }
            if (isset($userUpdateData['user_branch'])) {
                unset($userUpdateData['user_branch']);
            }
            $updateData = $userUpdateData;





            // 如果密码被传入并且不为空，进行MD5加密
            if (isset($updateData['user_password']) && !empty($updateData['user_password'])) {
                $updateData['user_password'] = md5($updateData['user_password']);
            }


            // 插入 user 表
            Db::name('user')->insert($updateData);

           //按照用户名查询新插入用户的id
            $user_id=Db::name('user')->where('user_username',$data['user_username'])->value('user_id');




            // 处理用户与分支机构关系更新
            if (isset($data['user_branch'])) {
                $userBranchData = $data['user_branch'];




                // 插入新的关联记录
                foreach ($userBranchData as $branch) {
                    Db::name('user_branch')->insert([
                        'user_id'=>$user_id,
                        'branch_id' => $branch,
                    ]);


                }

            }

            // 处理用户与角色关系更新
            if (isset($data['user_role'])) {
                $userRoleData = $data['user_role'];



                // 插入新的关联记录
                foreach ($userRoleData as $role) {
                    Db::name('user_role')->insert([
                        'user_id'=>$user_id,
                        'role_id' => $role,
                    ]);
                }
            }

            // 提交事务
            Db::commit();

            // 返回成功信息
            return json(['code'=>200,'msg'=>'插入成功']);
        } catch (Exception $e) {
            // 发生错误，回滚事务
            Db::rollback();

            // 记录错误或返回错误信息
            return json(['msg' => 'Failed to inster user information: ' . $e->getMessage()], 500);
        }

    }
    //根据user_id删除用户
    public function delete_userInfo()
    {
        $user_id=Request::param('id');
        if(Db::name('user')->where('user_id',$user_id)->update(['user_deleted'=>1])){
            return json(['code'=>200,'msg'=>'删除成功']);
        }else{
            return json(['code'=>-1,'msg'=>'删除失败']);
        }

    }
    //查询所有未审核用户
    public function get_AuditUse()
    {
        $userId = $this->request->auth['data']->user->user_id;
        // 根据用户ID获取公司ID
        $companyId = Db::name('user')->where('user_id', $userId)->value('user_company_id');

        $AuditUse = Db::table('AuditUse')
            ->where('AuditUser_company_id', $companyId)
            ->where('AuditUser_state','未审核')
            ->select();
        return json(['code'=>200,'msg'=>'查询成功','data'=>$AuditUse]);

    }
    //查询所有已被拒绝的用户
    public function get_RejectUse()
    {
        $userId = $this->request->auth['data']->user->user_id;
        // 根据用户ID获取公司ID
        $companyId = Db::name('user')->where('user_id', $userId)->value('user_company_id');

        $RejectUse = Db::table('AuditUse')
            ->where('AuditUser_company_id', $companyId)
            ->where('AuditUser_state','已拒绝')
            ->select();
        return json(['code'=>200,'msg'=>'查询成功','data'=>$RejectUse]);
        }
    //审核用户
    public function AuditUser()
    {
        $AuditUser_id=Request::param('id');
      //开启事务，将状态改为已审核
          try {
            // 开启事务
            Db::startTrans();

            // 更新 user 表
            Db::table('AuditUse')->where('AuditUser_id',$AuditUser_id)->update(['AuditUser_state'=>'已审核']);
            //将AuditUse表的数据插入到user表中
              $userData = Db::table('AuditUse')->where('AuditUser_id',$AuditUser_id)->find();
              $AuditUserData['user_deleted'] = 0;
              $AuditUserData['user_switch'] = 1;
              $AuditUserData['user_root'] = 0;
              $AuditUserData['user_password'] =$userData['AuditUser_password'];
              $AuditUserData['user_company_id'] =$userData['AuditUser_company_id'];
              $AuditUserData['user_username'] =$userData['AuditUser_username'];
              $AuditUserData['user_name'] =$userData['AuditUser_name'];
              $AuditUserData['user_phone'] =$userData['AuditUser_phone'];
              $AuditUserData['user_openid'] =$userData['AuditUser_openid'];
              $AuditUserData['user_sex']=$userData['AuditUser_sex']=='男'?1:2;
              // 插入 user 表
              Db::table('user')->insert($AuditUserData);

            // 提交事务
            Db::commit();

            // 返回成功信息
            return json(['code'=>200,'msg'=>'审核成功']);
        }
        catch (Exception $e) {
            // 发生错误，回滚事务
            Db::rollback();

            // 记录错误或返回错误信息
            return json(['msg' => 'Failed to audit user information: ' . $e->getMessage()], 500);
        }

    }
    //拒绝用户
    public function RejectUser()
    {
        $AuditUser_id=Request::param('id');
        //开启事务，将状态改为已拒绝
        try {
            // 开启事务
            Db::startTrans();

            // 更新 user 表
            Db::table('AuditUse')->where('AuditUser_id',$AuditUser_id)->update(['AuditUser_state'=>'已拒绝']);

            // 提交事务
            Db::commit();
            return json(['code'=>200,'msg'=>'拒绝成功']);
        }
        catch (Exception $e) {
            // 发生错误，回滚事务
            Db::rollback();

            // 记录错误或返回错误信息
            return json(['msg' => 'Failed to reject user information: ' . $e->getMessage()], 500);
        }
    }
    //撤回拒绝用户
    public function RecoverUser()
    {
        $AuditUser_id=Request::param('id');
        //开启事务，将状态改为未审核
        try {
            // 开启事务
            Db::startTrans();

            // 更新 user 表
            Db::table('AuditUse')->where('AuditUser_id',$AuditUser_id)->update(['AuditUser_state'=>'未审核']);

            // 提交事务
            Db::commit();

            // 返回成功信息
            return json(['code'=>200,'msg'=>'撤回成功']);
        }
        catch (Exception $e) {
            // 发生错误，回滚事务
            Db::rollback();

            // 记录错误或返回错误信息
            return json(['msg' => 'Failed to recover user information: ' . $e->getMessage()], 500);
        }
    }
    //删除已拒绝的注册用户
    public function delete_RejectUser()
    {
        $AuditUser_id=Request::param('id');
        if(Db::table('AuditUse')->where('AuditUser_id',$AuditUser_id)->delete()){
            return json(['code'=>200,'msg'=>'删除成功']);
        }else{
            return json(['code'=>-1,'msg'=>'删除失败']);
        }

    }
}